var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors')

var indexRouter = require('./routes/index');
var loginRouter = require('./routes/login');
var usersRouter = require('./routes/users');
var expressJWT = require("express-jwt");

const http=require('http');
const {Server}=require('socket.io');


var app = express();
app.use(cors())
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/upload', express.static(path.join(__dirname, 'upload')));

app.use('/', indexRouter);
app.use('/login', loginRouter)
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // // render the error page
  res.status(err.status || 500);
  res.render('error');
  console.log(err);
});


//创建HTTP服务器并集成Socket.IO
var server = http.createServer(app);
const io=new Server(server,{
  cors:{
     origin: "*", // 开发环境使用通配符
      // origin: "http://localhost:3001", // 替换为你的前端域名
      methods: ["GET", "POST"]
  }
})
// 导出服务器和Socket.IO实例

module.exports ={app,server,io};
